//
//  MNDForgotViewController.m
//  minidai
//
//  Created by Steven.Yung on 2017/5/25.
//  Copyright © 2017年 迷你金服. All rights reserved.
//

#import "MNDForgotViewController.h"
#import "NSString+JKNormalRegex.h"
#import "UIButton+JKCountDown.h"

@interface MNDForgotViewController ()

@property (weak, nonatomic) IBOutlet UITextField *userPhoneTextField;
@property (weak, nonatomic) IBOutlet UILabel *phoneTipLabel;
@property (weak, nonatomic) IBOutlet UIView *phoneBottomLineView;

@property (weak, nonatomic) IBOutlet UITextField *captchaTextField;
@property (weak, nonatomic) IBOutlet UILabel *captchaTipLabel;
@property (weak, nonatomic) IBOutlet UIView *captchaBottomLineView;

@property (weak, nonatomic) IBOutlet UITextField *passwordTextField;
@property (weak, nonatomic) IBOutlet UILabel *passwordTipLabel;
@property (weak, nonatomic) IBOutlet UIView *passwordBottomLineView;

@property (weak, nonatomic) IBOutlet UITextField *comfirmPasswordTextField;
@property (weak, nonatomic) IBOutlet UILabel *comfirmTipLabel;
@property (weak, nonatomic) IBOutlet UIView *comfirmBottomLineView;

@property (weak, nonatomic) IBOutlet UIButton *captchaBtn;

@property (copy, nonatomic) NSString *userPhone;
@property (copy, nonatomic) NSString *captcha;
@property (copy, nonatomic) NSString *password;
@property (copy, nonatomic) NSString *comfirmPwd;

@property(nonatomic, assign) BOOL isSendCaptcha;

@end

@implementation MNDForgotViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
//    RAC(self.captchaBtn, enabled) = [RACSignal combineLatest:@[RACObserve(self, userPhone)] reduce:^id (NSString *phone){
//        
//        return @(phone.length >= 11);
//    }];
    [[self.userPhoneTextField rac_textSignal] subscribeNext:^(NSString * _Nullable x) {
        if (x.length >= 11) {
            self.captchaBtn.enabled = YES;
        }else {
            self.captchaBtn.enabled = NO;
        }
    }];
    RAC(self, userPhone) = [RACSignal combineLatest:@[RACObserve(self, userPhoneTextField.text)] reduce:^id (NSString *phone) {
        
        return phone;
    }];
    RAC(self, captcha) = [RACSignal combineLatest:@[RACObserve(self, captchaTextField.text)] reduce:^id (NSString *captcha){
        return captcha;
    }];
    RAC(self, password) = [RACSignal combineLatest:@[RACObserve(self, passwordTextField.text)] reduce:^id (NSString *pwd){
        return pwd;
    }];
    RAC(self, comfirmPwd) = [RACSignal combineLatest:@[RACObserve(self, comfirmPasswordTextField.text)] reduce:^id (NSString *pwd){
        return pwd;
    }];
    
    __block UITextField *phoneTextField = self.userPhoneTextField;
    [self.userPhoneTextField.rac_textSignal subscribeNext:^(NSString * _Nullable x) {
        if (x.length > 11) {
            phoneTextField.text = [x substringToIndex:11];
        }
    }];
    
    __block UITextField *captchaTextField = self.captchaTextField;
    [self.captchaTextField.rac_textSignal subscribeNext:^(NSString * _Nullable x) {
        if (x.length > 5) {
            captchaTextField.text = [x substringToIndex:5];
        }
    }];
    
    __block UITextField *pwdTextField = self.passwordTextField;
    [self.passwordTextField.rac_textSignal subscribeNext:^(NSString * _Nullable x) {
        if (x.length > 16) {
            pwdTextField.text = [x substringToIndex:16];
        }
    }];
    
    __block UITextField *comfirmPwdTextField = self.comfirmPasswordTextField;
    [self.comfirmPasswordTextField.rac_textSignal subscribeNext:^(NSString * _Nullable x) {
        if (x.length > 16) {
            comfirmPwdTextField.text = [x substringToIndex:16];
        }
    }];
    
    [self setupUI];
    
}

- (void)setupUI {
    __weak __typeof(self)weakSelf = self;
    
    [self.userPhoneTextField bk_addEventHandler:^(id sender) {
        if (weakSelf.userPhoneTextField.text.length > 0) {
            weakSelf.phoneTipLabel.hidden = NO;
            weakSelf.phoneTipLabel.textColor = [UIColor colorWithRed:255/255.0 green:110/255.0 blue:63/255.0 alpha:1.0];
            weakSelf.phoneBottomLineView.backgroundColor = [UIColor colorWithRed:255/255.0 green:110/255.0 blue:63/255.0 alpha:1.0];
        }else {
            weakSelf.phoneTipLabel.hidden = YES;
        }
        
    } forControlEvents:UIControlEventEditingChanged];
    
    [self.userPhoneTextField bk_addEventHandler:^(id sender) {
        if(weakSelf.userPhoneTextField.text.length <= 0) {
            weakSelf.phoneTipLabel.hidden = YES;
        }
        weakSelf.phoneTipLabel.textColor = [UIColor colorWithRed:203/255.0 green:203/255.0 blue:203/255.0 alpha:1.0];
        weakSelf.phoneBottomLineView.backgroundColor = [UIColor colorWithRed:239/255.0 green:239/255.0 blue:244/255.0 alpha:1.0];
    } forControlEvents:UIControlEventEditingDidEnd];
    
    [self.captchaTextField bk_addEventHandler:^(id sender) {
        
        if (weakSelf.captchaTextField.text.length > 0) {
            weakSelf.captchaTipLabel.hidden = NO;
            weakSelf.captchaTipLabel.textColor = [UIColor colorWithRed:255/255.0 green:110/255.0 blue:63/255.0 alpha:1.0];
            weakSelf.captchaBottomLineView.backgroundColor = [UIColor colorWithRed:255/255.0 green:110/255.0 blue:63/255.0 alpha:1.0];
        }else {
            weakSelf.captchaTipLabel.hidden = YES;
        }
        
    } forControlEvents:UIControlEventEditingChanged];
    
    [self.captchaTextField bk_addEventHandler:^(id sender) {
        if(weakSelf.captchaTextField.text.length <= 0) {
            weakSelf.captchaTipLabel.hidden = YES;
        }
        weakSelf.captchaTipLabel.textColor = [UIColor colorWithRed:203/255.0 green:203/255.0 blue:203/255.0 alpha:1.0];
        weakSelf.captchaBottomLineView.backgroundColor = [UIColor colorWithRed:239/255.0 green:239/255.0 blue:244/255.0 alpha:1.0];
    } forControlEvents:UIControlEventEditingDidEnd];
    
    [self.passwordTextField bk_addEventHandler:^(id sender) {
        if (weakSelf.passwordTextField.text.length > 0) {
            weakSelf.passwordTipLabel.hidden = NO;
            weakSelf.passwordTipLabel.textColor = [UIColor colorWithRed:255/255.0 green:110/255.0 blue:63/255.0 alpha:1.0];
            weakSelf.passwordBottomLineView.backgroundColor = [UIColor colorWithRed:255/255.0 green:110/255.0 blue:63/255.0 alpha:1.0];
        }else {
            weakSelf.passwordTipLabel.hidden = YES;
        }
        
    } forControlEvents:UIControlEventEditingChanged];
    
    [self.passwordTextField bk_addEventHandler:^(id sender) {
        if(weakSelf.passwordTextField.text.length <= 0) {
            weakSelf.passwordTipLabel.hidden = YES;
        }
        weakSelf.passwordTipLabel.textColor = [UIColor colorWithRed:203/255.0 green:203/255.0 blue:203/255.0 alpha:1.0];
        weakSelf.passwordBottomLineView.backgroundColor = [UIColor colorWithRed:239/255.0 green:239/255.0 blue:244/255.0 alpha:1.0];
    } forControlEvents:UIControlEventEditingDidEnd];
    
    [self.comfirmPasswordTextField bk_addEventHandler:^(id sender) {
        if (weakSelf.comfirmPasswordTextField.text.length > 0) {
            weakSelf.comfirmTipLabel.hidden = NO;
            weakSelf.comfirmTipLabel.textColor = [UIColor colorWithRed:255/255.0 green:110/255.0 blue:63/255.0 alpha:1.0];
            weakSelf.comfirmBottomLineView.backgroundColor = [UIColor colorWithRed:255/255.0 green:110/255.0 blue:63/255.0 alpha:1.0];
        }else {
            weakSelf.comfirmTipLabel.hidden = YES;
        }
    } forControlEvents:UIControlEventEditingChanged];
    
    [self.comfirmPasswordTextField bk_addEventHandler:^(id sender) {
        if(weakSelf.comfirmPasswordTextField.text.length <= 0) {
            weakSelf.comfirmTipLabel.hidden = YES;
        }
        weakSelf.comfirmTipLabel.textColor = [UIColor colorWithRed:203/255.0 green:203/255.0 blue:203/255.0 alpha:1.0];
        weakSelf.comfirmBottomLineView.backgroundColor = [UIColor colorWithRed:239/255.0 green:239/255.0 blue:244/255.0 alpha:1.0];
    } forControlEvents:UIControlEventEditingDidEnd];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)showOrHidePasswordAction:(UIButton *)sender {
    sender.selected = !sender.isSelected;
    
    self.passwordTextField.secureTextEntry = !sender.isSelected;
    self.comfirmPasswordTextField.secureTextEntry = !sender.isSelected;
}



- (IBAction)sendPhoneCaptchaAction:(id)sender {
    
    [self.view endEditing:YES];
    if (self.userPhone.length <= 0) {
        [NetworkProgressHUD showHudMsg:@"请输入手机号"];
        return;
    }
    
//    if (!self.userPhone.jk_isMobileNumber) {
//        [NetworkProgressHUD showHudMsg:@"手机号码不正确"];
//        return;
//    }
    WeakSelf(self);
//    UIButton *sendBtn = sender;
    [NetworkProgressHUD showHud];
    [APIManager sendRequestWithPath:API_FORGOT_SEND_PHONE_CAPTCHA parameters:[MNDSign signedParamWithDict:@{@"user_phone": self.userPhone}] method:kXMHTTPMethodPOST onSuccess:^(ResponseModel *responseModel) {
        
        if (responseModel.status == ResponseSuccess) {
            [weakself.captchaBtn jk_startTime:30 title:@"重新获取" waitTittle:@"秒后重发"];
            [NetworkProgressHUD showHudMsg:@"验证码已发送"];
            weakself.isSendCaptcha = YES;
        } else {
            NSDictionary *dict = responseModel.msg;
            if (dict && dict.count > 0) {
                [NetworkProgressHUD showHudMsg:dict[@"error"]];
            } else {
                [NetworkProgressHUD showHudMsg:@"发送失败，请重新发送"];
            }
        }
    } onFailure:^(NSError *error) {
        [NetworkProgressHUD showHudNetworkError:error];
    }];
}

- (IBAction)submitAction:(id)sender {
    [self.view endEditing:YES];
    
    if (!self.isSendCaptcha) {
        [NetworkProgressHUD showHudMsg:@"请先获取手机验证码"];
        return;
    }
    
    if (self.userPhone.length <= 0) {
        [NetworkProgressHUD showHudMsg:@"请输入手机号码"];
        return;
    }
//    if (!self.userPhone.jk_isMobileNumber) {
//        [NetworkProgressHUD showHudMsg:@"手机号码不正确"];
//        return;
//    }
    if (self.captcha.length <= 0) {
        [NetworkProgressHUD showHudMsg:@"请输入验证码"];
        return;
    }
    if (self.password.length <= 0) {
        [NetworkProgressHUD showHudMsg:@"请输入新密码"];
        return;
    }
    if (self.comfirmPwd.length <= 0) {
        [NetworkProgressHUD showHudMsg:@"请重新输入新密码"];
        return;
    }
    
    [self resetPassword];
}

- (void)resetPassword {
    WeakSelf(self);
    [NetworkProgressHUD showHud];
    
    NSDictionary *params = @{
                             @"user_phone": self.userPhone,
                             @"phone_captcha": self.captcha,
                             @"new_login_password": self.password,
                             @"confirm_login_password": self.comfirmPwd};
    [APIManager sendRequestWithPath:API_LOGIN_PASSWORD_FORGOT parameters:[MNDSign signedParamWithDict:params] method:kXMHTTPMethodPOST onSuccess:^(ResponseModel *responseModel) {
        
        if (responseModel.status == ResponseSuccess) {
            
            [NetworkProgressHUD showHudMsg:@"密码修改成功，请重新登录"];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [weakself.navigationController popViewControllerAnimated:YES];
            });
        } else {
            NSDictionary *dict = responseModel.msg;
            if (dict && dict.count > 0) {
                [NetworkProgressHUD showHudMsg:dict[@"error"]];
            } else {
                [NetworkProgressHUD showHudMsg:@"密码修改失败，请重试"];
            }
        }
    } onFailure:^(NSError *error) {
        [NetworkProgressHUD showHudNetworkError:error];
    }];
}

@end
